package cn.e2win.biz.comm;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.e2win.base.controller.MyException;
import cn.e2win.base.entity.MsgLogs;
import cn.e2win.biz.sms.MsgService;


public class SmsSender implements Runnable {
	final String HTTP_URL = "http://utf8.sms.webchinese.cn/?Uid=giro&Key=b5ef425b9ad13dc4bc0b&smsMob=";
	int isProduction = 1;

	static ExecutorService executor = Executors.newFixedThreadPool(3);
	private MsgLogs msgLog;
	private MsgService service;
	

	public SmsSender() {

	}
	public SmsSender(MsgService service, MsgLogs msglog) {
		this.service = service;
		this.msgLog = msglog;
	}

	@Override
	public void run() {
		System.err.println("开始调用线程！！");
		long t = System.currentTimeMillis();
		try {
			sendMsg();
		} catch (MyException e) {
			e.printStackTrace();
		}
		t = System.currentTimeMillis() - t;
		System.err.println("线程调用结束！！耗时======" + t);
	}

	public String sendNow() throws MyException{
		return sendMsg();
	}
	public void sendByThread(){
		executor.execute(this);
	}
	
	
	
	
	
	
	
	private String sendMsg() throws MyException {
		if(service.getCompany(msgLog).getSmsQty()<=0){
			throw new MyException("可用短信条数不足，请充值后使用!");
		}
		String sTotalString = sendMsg(msgLog.getToNo(), msgLog.getMsgText());		
		msgLog.setMsgStatus(sTotalString);
		service.updateCompanySmsQty(msgLog);
		return sTotalString;
	}
	
	
	
	private String sendMsg(String tellNo, String msg) throws MyException{
		if (isProduction == 0) {
			System.err.println("initIsProduction();");
		}
		if (isProduction != 1) {
			System.err.println("send msg == " + msgLog.getMsgText());
			return "测试环境，不发短信！";
		}
		String sTotalString = "";
		URL url;
		long t1 = System.currentTimeMillis();
		try {
			url = new URL(HTTP_URL + tellNo + "&smsText=" + URLEncoder.encode("【会员易】" + msg, "UTF-8"));
			URLConnection URLconnection = url.openConnection();
			HttpURLConnection httpConnection = (HttpURLConnection) URLconnection;
			int responseCode = httpConnection.getResponseCode();
			System.err.println("responseCode==" + responseCode);
			if (responseCode == HttpURLConnection.HTTP_OK) {
				InputStream urlStream = httpConnection.getInputStream();
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlStream));
				String sCurrentLine = "";
				while ((sCurrentLine = bufferedReader.readLine()) != null) {
					sTotalString += sCurrentLine;
				}
			} else {
				sTotalString = "网络连接异常";
			}
			
		} catch (Exception e) {
			t1 = System.currentTimeMillis() - t1;
			System.err.println("发送失败！！！！耗时====" + t1);
			sTotalString = "不名原因失败";
			e.printStackTrace();
		}
		return sTotalString;
	}
	private void initIsProduction() {
		try {
			Enumeration<NetworkInterface> netInterfaces = NetworkInterface
					.getNetworkInterfaces();
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface nif = netInterfaces.nextElement();
				Enumeration<InetAddress> iparray = nif.getInetAddresses();
				while (iparray.hasMoreElements()) {
					String ip = iparray.nextElement().getHostAddress();
					if ("192.168.1.178".equals(ip)) {
						isProduction = 1;
					}
				}
			}
			if (isProduction != 1) {
				isProduction = -1;
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

	public static void main(String[] args) {
		ExecutorService executor = Executors.newFixedThreadPool(5);
		for (int i = 0; i < 10; i++) {
			Runnable worker = new SmsSender();
			executor.execute(worker);
		}
		executor.shutdown(); // This will make the executor accept no new
								// threads and finish all existing threads in
								// the queue
		while (!executor.isTerminated()) { // Wait until all threads are
											// finish,and also you can use
											// "executor.awaitTermination();" to
											// wait
		}
		System.out.println("Finished all threads");

	}

}
